#include "../include/head.h"
#include "../include/threadPool.h"



/* Usage*/
void* threadFunc(void * arg)
{ 
    threadPool_t *pthreadPool = (threadPool_t *)arg;
    while(1)
    {
        //工人线程 后出队 消费者
        pthread_mutex_lock(&pthreadPool->mutex);
        while(pthreadPool->taskQueue.size == 0 && pthreadPool->exitFlag == 0)
        {
            pthread_cond_wait(&pthreadPool->cond,&pthreadPool->mutex);
        }
        //检查退出状态
        if(pthreadPool->exitFlag == 1)
        { 
            printf("i am worker,i am going to exit!\n");
            pthread_mutex_unlock(&pthreadPool->mutex);
            pthread_exit(NULL);
        }
        if(pthreadPool->taskQueue.phead == NULL)
        { 
            printf("taskQueue phead is NULL\n");
            pthread_mutex_unlock(&pthreadPool->mutex);
            continue;
        }
        int netfd = pthreadPool->taskQueue.phead->netfd;
        printf("i am worker,netfd = %d\n",netfd);
        head_dele(&pthreadPool->taskQueue);
        pthread_mutex_unlock(&pthreadPool->mutex);

        char username[100];
        serLog(netfd,username);

        commandStack_t curPath;
        /* curPath.username = username; */
        /* printf("--------------%s-------------\n",username); */
        if(init_stack(&curPath) == 0){
            printf("stack->top=%d\n",curPath.top);
            memcpy(curPath.username, username, strlen(username));
            char buf_id[4];
            mysql_use_select("id","path","/",buf_id,&curPath);
            push_stack(&curPath,atoi(buf_id));
        }else{
            printf("init failed\n");
        }

        while(1){
            do_comm(netfd, &curPath);
        }
        close(netfd);
        free(curPath.username);
    }
    return 0;

}


int makeWorker(threadPool_t *pthreadPool)
{
    for(int i = 0;i<pthreadPool->workerArr.workernum;i++)
    {
        pthread_create(&pthreadPool->workerArr.tidArr[i],NULL,threadFunc,pthreadPool);
    }
    return 0;
}
